<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	const token = uni.getStorageSync('info')
	if (!token) {
		uni.navigateTo({
			url: '/pages/login/login'
		})
	}
	interface obj {
		value:string
		phone:string
	}
	const values = ref('')
	let arr = ref<Array<obj>>([])
	const sub = () => {
		if (uni.getStorageSync('socketOpen')&&values.value) {
			arr.value.push({ value: values.value, phone: token.phone })
			uni.sendSocketMessage({
				data: JSON.stringify({ value: values.value, phone: token.phone }),
			});
			values.value = ''
		} else {
			console.log('WebSocket is not connected');
		}
	};
	onMounted(() => {
		uni.connectSocket({
			url: 'ws://localhost:8080',
			success: data => {
				console.log("连接成功",data);
			}
		});
		uni.onSocketOpen(function () {
			console.log('WebSocket connected');
			uni.setStorageSync('socketOpen', true);
		});
		uni.onSocketMessage((res) => {
			const data = JSON.parse(res.data);
			console.log(data);
			arr.value = [...data]
			
		});
		uni.onSocketClose(function () {
			console.log('WebSocket disconnected');
			uni.setStorageSync('socketOpen', false);
		});
	})
</script>


<template>
	<view class="content">
		<view class="main">
			<view v-for="item in arr" :key="item">
				<div :class="item.phone == token.phone? 'right':'left'">{{item.value}}</div>
			</view>
		</view>
		<view class="foot">
			<input type="text" class="cont" v-model="values" />
			<button @click=sub>提交</button>
		</view>
	</view>
</template>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}

	.title {
		font-size: 36px;
		color: #8f8f94;
	}

	.foot {
		position: fixed;
		width: 100%;
		bottom: 0;
	}

	.cont {
		width: 100%;
		background-color: #eee;
		height: 80rpx;
	}
	.right{
		width: 100vw;
		text-align: right;
	}
	.left{
		width: 100vw;
		text-align: left;
	}
</style>